﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using WURFL;
using loveyou.Models;

namespace loveyou.Core
{
    public class GlobalConfig
    {
        /// <summary>
        /// 在线用户列表
        /// </summary>
        public static Dictionary<string, UserInfo> OnlineUserList = new Dictionary<string, UserInfo>(StringComparer.CurrentCultureIgnoreCase);

        public static string CurrentUserName
        {
            get
            {
                var httpContext = HttpContext.Current;
                var user = httpContext.User;
                string userName = null;

                #region WURFL
                var userAgent = httpContext.Request.UserAgent;
                // Call WURFL
                var startTime = DateTime.Now;
                var deviceInfo = MvcApplication.WurflManager.GetDeviceForRequest(userAgent);
                var endTime = DateTime.Now;
                #endregion

                if (user.Identity.IsAuthenticated)
                {
                    if (OnlineUserList.ContainsKey(user.Identity.Name)
                        && OnlineUserList[user.Identity.Name].DeviceKey==deviceInfo.Id)
                    {
                        userName = user.Identity.Name;//用户已经注册
                    }
                }

                if (string.IsNullOrEmpty(userName))
                {
                    //新建用户
                    userName = GetNewUserName();
                    httpContext.Request.Cookies.Add(new HttpCookie("UserTicket", userName));
                    FormsAuthentication.SetAuthCookie(userName, true);

                    UserInfo userInfo = new UserInfo()
                    {
                        DeviceKey = deviceInfo.Id,
                        UserName = userName,
                        DeviceInfo = deviceInfo
                    };
                    OnlineUserList.Add(userName, userInfo);
                    //System.Web.HttpCookie lcookie = System.Web.HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
                }

                return userName;
            }
        }

        /// <summary>
        /// 获取新用户名
        /// </summary>
        /// <returns></returns>
        private static string GetNewUserName()
        {
            int baseIndex = OnlineUserList.Count + 100;
            do
            {
                baseIndex++;
            } while (OnlineUserList.ContainsKey(baseIndex.ToString("X")));
            return baseIndex.ToString("X");
        }
    }
}